<template>
  <div class="page-index-img">
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            prop="status"
            :label="$t('product.status') + ':'"
          >
            <el-select
              v-model="searchForm.status"
              clearable
              :placeholder="$t('product.status')"
            >
              <el-option
                v-for="item in status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="imgType"
            :label="$t('platform.client') + ':'"
          >
            <el-select
              v-model="searchForm.imgType"
              clearable
              :placeholder="$t('platform.client')"
            >
              <el-option
                :label="$t('platform.mobile')"
                :value="0"
              />
              <el-option
                :label="$t('platform.PCTerminal')"
                :value="1"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('crud.searchBtn') }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch(searchFormRef)"
            >
              {{ $t('crud.emptyBtn') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <el-checkbox
          v-model="selectAll"
          class="all-check-btn"
          @change="onSelectAll"
        >
          {{
            $t('brand.selectAll')
          }}
        </el-checkbox>
        <span
          v-if="dataListSelections.length"
          class="had-selected"
        >{{ $t('brand.selected') }} {{ dataListSelections.length }}</span>
        <div
          v-if="isAuth('admin:indexImg:save')"
          class="default-btn primary-btn"
          @click="onAddOrUpdate()"
        >
          {{ $t('crud.addTitle') }}
          <el-tooltip
            class="item"
            effect="dark"
            :content="$t('publics.maxIndexImgNumOfPlatform')"
            placement="top"
          >
            <el-icon
              class="tips"
            >
              <WarningFilled />
            </el-icon>
          </el-tooltip>
        </div>
        <div
          v-if="isAuth('admin:indexImg:delete')"
          :class="[!dataListSelections.length ? 'disabled-btn' : '', 'default-btn']"
          @click.stop="onDelete()"
        >
          {{ $t('sys.batchDelete') }}
        </div>
      </div>
      <div class="table-con">
        <el-table
          ref="imgTableRef"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          :row-style="{ height: '100px' }"
          style="width: 100%"
          @selection-change="onSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column
            :label="$t('temp.rotaImg')"
            align="center"
            prop="imgUrl"
            width="350"
          >
            <template #default="scope">
              <div class="table-cell-image banner-img">
                <img
                  v-if="scope.row.imgUrl"
                  alt=""
                  :src="resourcesUrl + scope.row.imgUrl"
                >
                <img
                  v-else
                  alt=""
                  src="~@/assets/img/def.png"
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="seq"
            :label="$t('temp.sequence')"
          />
          <el-table-column
            align="center"
            :label="$t('publics.status')"
          >
            <template #default="scope">
              <span>{{ [$t('publics.disable'), $t('publics.normal')][scope.row.status] }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="imgType"
            :label="$t('platform.client')"
          >
            <template #default="scope">
              <span>{{ [$t('platform.mobile'), $t('platform.pc')][scope.row.imgType] }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$t('crud.menu')"
            width="220"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('admin:indexImg:update')"
                  class="default-btn text-btn"
                  @click="onAddOrUpdate(scope.row.imgId)"
                >
                  {{ $t('temp.modify') }}
                </div>
                <div
                  v-if="isAuth('admin:indexImg:delete')"
                  class="default-btn text-btn"
                  @click="onDelete(scope.row.imgId)"
                >
                  {{ $t('text.delBtn') }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        @update:page-size="onPageSizeChange"
        @update:current-page="onPageChange"
      />
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="refreshChange"
    />
  </div>
</template>

<script setup>
import { WarningFilled } from '@element-plus/icons-vue'
import AddOrUpdate from './add-or-update.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { isAuth } from '@/utils/index.js'
const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL
const status = [
  {
    label: $t('publics.disable'),
    value: 0
  },
  {
    label: $t('publics.normal'),
    value: 1
  }
]
const page = ref({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
onMounted(() => {
  onGetDataList(page.value)
})

// 获取数据列表
let tempSearchForm = null // 保存上次点击查询的请求条件
const dataListLoading = ref(false)
const dataList = ref([])
const searchForm = ref({
  status: null,
  imgType: null
})
const onGetDataList = (pageParam, newData = false) => {
  if (page.value) {
    const size = Math.ceil(page.value.total / page.value.pageSize)
    page.value.currentPage = page.value.currentPage > size ? size : page.value.currentPage
  }
  dataListLoading.value = true
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm.value))
  }
  http({
    url: http.adornUrl('/admin/indexImg/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.value.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.value.pageSize : pageParam.pageSize
        },
        tempSearchForm
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.value.total = data.total
    page.value.currentPage = data.current ? data.current : 1
    dataListLoading.value = false
  })
}

// 新增 / 修改
const addOrUpdateVisible = ref(false)
const addOrUpdateRef = ref(null)
const onAddOrUpdate = id => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id)
  })
}
// 删除
const dataListSelections = ref([])
const onDelete = id => {
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.imgId
  })
  if (!ids.length) {
    return
  }
  ElMessageBox.confirm(
    `${$t('sys.makeSure')}${id ? $t('text.delBtn') : $t('publics.batchDelete')}${$t('text.menu')}?`,
    $t('text.tips'),
    {
      confirmButtonText: $t('crud.filter.submitBtn'),
      cancelButtonText: $t('crud.filter.cancelBtn'),
      type: 'warning'
    }
  ).then(() => {
    http({
      url: http.adornUrl('/admin/indexImg'),
      method: 'delete',
      data: http.adornData(ids, false)
    }).then(() => {
      page.value.total = page.value.total - ids.length
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          refreshChange()
        }
      })
    })
  })
}
// 条件查询
const onSearch = (newData = false) => {
  page.value.currentPage = 1
  onGetDataList(page.value, newData)
}
// 刷新回调
const refreshChange = () => {
  onGetDataList(page.value)
}
// 多选变化
const selectAll = ref(false)
const onSelectionChange = val => {
  dataListSelections.value = val
  selectAll.value = val.length === dataList.value.length
}
/**
 * 全选按钮
 */
const imgTableRef = ref(0)
const onSelectAll = () => {
  selectAll.value = imgTableRef.value.selection?.length < dataList.value?.length
  imgTableRef.value?.toggleAllSelection()
}
const onPageSizeChange = val => {
  page.value.pageSize = val
  onGetDataList(page.value)
}
const onPageChange = val => {
  page.value.currentPage = val
  onGetDataList(page.value)
}
const searchFormRef = ref(null)
const onResetSearch = formName => {
  formName.resetFields()
}
</script>

<style lang="scss" scoped>
.page-index-img {
  .banner-img {
    width: auto;
    height: 94px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
  }
.tips{
  top: 2px;
}
}
</style>
